package com.wsoft.bpm.component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.bpmn.model.*;
import org.activiti.editor.language.json.converter.BaseBpmnJsonConverter;
import org.activiti.editor.language.json.converter.UserTaskJsonConverter;

import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @Author zhonglj
 * @Date 2024-09-27 16:46
 */
public class CustomUserTaskJsonConverter extends UserTaskJsonConverter {
    public static final  String PROPERTIES_WSOFT_MODE = "wsoftElement";

    @Override
    protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
        super.convertElementToJson(propertiesNode, baseElement);
        UserTask userTask = (UserTask) baseElement;

        //解析新增属性的业务逻辑
        Map<String, List<ExtensionElement>> customerProperties = userTask.getExtensionElements();
        if(customerProperties !=null && customerProperties.get(PROPERTIES_WSOFT_MODE) !=null){
            ExtensionElement e = customerProperties.get(PROPERTIES_WSOFT_MODE).get(0);
            setPropertyValue(PROPERTIES_WSOFT_MODE, e.getElementText(), propertiesNode);
        }
    }

    @Override
    protected FlowElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap) {
        FlowElement flowElement = super.convertJsonToElement(elementNode,
                modelNode, shapeMap);
        UserTask userTask = (UserTask)flowElement;
        CustomProperty customProperty = new CustomProperty();
        customProperty.setName(PROPERTIES_WSOFT_MODE);
        customProperty.setSimpleValue(this.getPropertyValueAsString(PROPERTIES_WSOFT_MODE,elementNode ));
        userTask.getCustomProperties().add(customProperty);

        return flowElement;
    }

    public static void fillTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap,
                                 Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap) {

        fillJsonTypes(convertersToBpmnMap);
        fillBpmnTypes(convertersToJsonMap);
    }

    public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
        convertersToBpmnMap.put(STENCIL_TASK_USER, CustomUserTaskJsonConverter.class);
    }

    public static void fillBpmnTypes(Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap) {
        convertersToJsonMap.put(UserTask.class, CustomUserTaskJsonConverter.class);
    }

}
